<template>
    <PageWrapper v-loading="loading" loading-tip="加载中...">
        <div class="p-4 p-4-tag">
            <div class="tag">
                <div class="form-box">
                    <BasicForm @register="registerForm" />
                </div>
                <div class="table-box">
                    <BasicTable
                        @register="registerTable"
                        :columns="columns"
                        :dataSource="tableData"
                        :canResize="false"
                        :showIndexColumn="false"
                        :striped="true"
                        :bordered="true"
                        :pagination="false"
                        :actionColumn="hasPermission(['3-2-edit', '3-2-del']) ? actionColumn : undefined"
                    >
                    <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'action' && hasPermission(['3-2-edit', '3-2-del'])">
                        <TableAction
                        :actions="[
                            {
                                label: '编辑',
                                icon: 'ant-design:edit-outlined',
                                ifShow: hasPermission('3-2-edit'),
                                onClick: (e) => {
                                    e.stopPropagation();
                                    handleEdit(record);
                                },
                            },
                            {
                                label: '字典配置',
                                icon: 'ant-design:edit-outlined',
                                ifShow: hasPermission('3-2-edit'),
                                onClick: (e) => {
                                    e.stopPropagation();
                                    handleItem(record);
                                },
                            },
                            {
                            label: '删除',
                            icon: 'ant-design:delete-outlined',
                            ifShow: hasPermission('3-2-del'),
                            onClick: (e) => {
                                e.stopPropagation();
                                handleDelete(record);
                            },
                            },
                        ]"
                        />
                    </template>
                    </template>
                    <template #toolbar>
                        <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
                        <a-button class="btn-box-item" type="primary" @click="throttleSubmit">查询</a-button>
                        <a-button
                            class="btn-box-item"
                            type="primary"
                            @click="handleAdd"
                            v-if="hasPermission('3-2-add')"
                        >
                            新增
                        </a-button>
                        </template>
                    </BasicTable>
                    <div class="flex py-2 items-center justify-end pagination-box">
                        <a-pagination
                        :show-total="(total) => `共 ${total} 条数据`"
                        showSizeChanger
                        size="small"
                        :current="paginationInfo.data.current"
                        :pageSize="paginationInfo.data.pageSize"
                        :total="paginationInfo.data.total"
                        @change="handlePageChange"
                        />
                    </div>
                </div>
            </div>
        </div>
         <!-- 新增或编辑的弹窗 -->
        <modelByDetail
        :info="detailForm"
        @register="registerByDetail"
        @submit-success="handelUpateTable"
        />
        <!--字典配置抽屉-->
        <DictItemList @register="registerDrawer" />
    </PageWrapper>
</template>
<script lang="ts" setup>
    import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
    import { PageWrapper } from '/@/components/Page';
    import { ref, onMounted, reactive, h } from 'vue';
    import { useDrawer } from '/@/components/Drawer';
    import { BasicColumn } from '/@/components/Table/src/types/table';
    import { BasicTable, TableAction, useTable } from '/@/components/Table';
    import { usePermission } from '/@/hooks/web/usePermission';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { useModal } from '/@/components/Modal';
    import { Pagination } from 'ant-design-vue';
    import DictItemList from '/@/views/project/dataDictionary/components/DictItemList.vue';
    import modelByDetail from '/@/views/project/dataDictionary/components/modelByDetail.vue';
    import { useDebounceFn } from '@vueuse/core';
    import { getdataDic,deldicmodel } from '/@/api/dataDictionary/index';

    const APagination = Pagination;
    const { t } = useI18n();
    const { hasPermission } = usePermission();
    let loading = ref(false);
    let isShowBatchDel = ref(false);
    let loadingByBtn = ref(false);
    let tableData = reactive([]);
    let Parameters = '[""]';
    // 分页信息
    let paginationInfo = reactive({
        data: {
            pageSize: 50,
            total: 0,
            current: 1,
        },
    })
     // 表格表头
    let columns: BasicColumn[] = [
        {
            title: '字典名称',
            dataIndex: 'Name',
        },
        {
            title: '字典编码',
            dataIndex: 'Code',
        },
        {
            title: '状态',
            dataIndex: 'Statustext',
        },
        {
            title: '排序',
            dataIndex: 'OrderNo',
        },
    ];
        // 表单内容
    const schemas: FormSchema[] = [
        {
            field: 'Name',
            component: 'Input',
            label: '字典名称',
            colProps: {
            span: 6,
            },
        },
        {
            field: 'Code',
            component: 'Input',
            label: '字典编码',
            colProps: {
            span: 6,
            },
        },
    ]
    let detailForm = reactive({
        type: 'add',
        data: {},
    });
    // 操作栏
    let actionColumn = {
        width: 150,
        title: '操作',
        dataIndex: 'action',
        // slots: { customRender: 'action' },
    };
     //字典配置drawer
    const [registerDrawer, { openDrawer }] = useDrawer();
    const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] = useModal();
    const [registerTable] = useTable();
    const { createConfirm, createMessage } = useMessage();
    const [registerForm, { validateFields, setFieldsValue }] = useForm({
        labelWidth: 100,
        schemas: schemas,
        showActionButtonGroup: false,
        actionColOptions: {
        span: 24,
        },
    });
    const throttleSubmit = useDebounceFn(handleSubmit, 500);
    const throttleReset = useDebounceFn(handleResetFields, 500);
     // 重置按钮点击事件
    async function handleResetFields() {
        setFieldsValue({
            dictName: '',
            dictCode: '',
        });
        paginationInfo.data.current = 1;
        getTableData();
    }
     // 新增或编辑成功事件
        function handelUpateTable() {
        detailForm.type = 'add';
        detailForm.data = {};
        closeModalByDetail();
        getTableData();
    }
    // 查询按钮点击事件
    async function handleSubmit() {
        try {
        let res = await validateFields();
        console.log(`output->res`, res);
        getTableData(res);
        } catch {}
    }
    // 获取字典数据
  async function getTableData(params = {}) {
    try {
      loading.value = true;
      let StatusObj = {
        1: '启用',
        2: '禁用',
      };
      let res = await getdataDic([
        {
            dictName: '',
            dictCode: '',
            page: paginationInfo.data.current,
            pageSize: paginationInfo.data.pageSize,
            ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      tableData = res.Items.map((item) => {
        item.Statustext = StatusObj[item.Status];
        return item;
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
     // 分页事件
    function handlePageChange(page, pageSize) {
        paginationInfo.data.current = page;
        paginationInfo.data.pageSize = pageSize;
       getTableData();
    }
    // 新增
    function handleAdd() {
        detailForm.type = 'add';
        detailForm.data = {Status:1, OrderNo: 100};
        openModalByDetail();
    }
    // 编辑
    function handleEdit(params) {
        detailForm.type = 'update';
        detailForm.data = params;
        openModalByDetail();
    }
  // 删除
  function handleDelete(params) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该字典（${params.Name}）`),
      onOk: async () => {
        loading.value = true;
        try {
          await deldicmodel([params]);
          createMessage.success(t('layout.setting.operatingTitle'));
          getTableData();
          loading.value = false;
        } catch (error) {
          loading.value = false;
        }
      },
    });
  }

    /**
   * 字典配置
   */
   function handleItem(record) {
        openDrawer(true, {
            Code: record.Code,
            dictId: record.Id,
        });
    }
    onMounted(async () => {
    getTableData();
  });
</script>
<style lang="less" scoped> 
.p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .form-box {
      padding: 5px;

      ::v-deep(.ant-form-item) {
        margin: 0 5px;
      }
    }

    .table-box {
      flex: 1;
    }

    .btn-box {
      display: flex;
      align-items: center;

      .btn-box-item {
        margin: 0 5px;
      }
    }

    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }

  ::v-deep .ant-col:last-child {
    .ant-form-item {
      margin-bottom: 0px;
    }
  }
</style>